package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.*;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MakeFriendManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Reference
    private RecommendUserService recommendUserService;

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private MovementService movementService;

    @Reference
    private QuestionService questionService;

    @Reference
    private VisitorService visitorService;

    @Reference
    private UserLocationService userLocationService;

    @Reference
    private FriendService friendService;


    //今日佳人
    public RecommendUserVo findTodayBest() {

        //获取登录用户id
        Long userId = UserHolder.get().getId();

        //获取到缘分值最大的佳人
        RecommendUser recommendUser = recommendUserService.findMaxScore(userId);

        //3. 如果没有推送用户,将1号用户推送过去
        if (recommendUser == null) {
            //主动构建1号
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);//推荐用户
            recommendUser.setToUserId(userId);//退给谁
            recommendUser.setScore(99D);//缘分值
        }

        RecommendUserVo recommendUserVo = new RecommendUserVo();

        //获取推荐佳人的个人信息
        UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());
        recommendUserVo.setUserInfo(userInfo);
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());

        return recommendUserVo;
    }



    //推荐用户列表
    public PageBeanVo findRecommendUser(Integer pageNum, Integer pageSize) {

        //获取登录用户id
        Long userId = UserHolder.get().getId();

        //根据登录用户id调用service分页查询
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUser(userId, pageNum, pageSize);

        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();

        if (CollectionUtil.isEmpty(recommendUserList)) {
            //手动封装8个用户,放入recommendUserList
            for (Long i = 2L; i < 9L; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(i);//推荐用户
                recommendUser.setToUserId(userId);//退给谁
                recommendUser.setScore(RandomUtil.randomDouble(80, 90));//缘分值

                recommendUserList.add(recommendUser);
            }

        }

        List<RecommendUserVo> recommendUserVoList = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {

            RecommendUserVo recommendUserVo = new RecommendUserVo();
            recommendUserVo.setUserInfo(userInfoService.findById(recommendUser.getUserId()));
            recommendUserVo.setFateValue(recommendUser.getScore().longValue());

            recommendUserVoList.add(recommendUserVo);
        }

        pageBeanVo.setItems(recommendUserVoList);

        return pageBeanVo;
    }


    //佳人详情
    public RecommendUserVo findPersonalInfo(Long recommendUserId) {

        Long userId = UserHolder.get().getId();
        //2. 调用recommendUserService查询二人缘分值
        RecommendUser recommendUser = recommendUserService.findRecommendUser(userId, recommendUserId);

        //3. 调用userInfoservice查询佳人信息
        UserInfo userInfo = userInfoService.findById(recommendUserId);

        //封装
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        recommendUserVo.setUserInfo(userInfo);

        if (recommendUser == null) {
            recommendUserVo.setFateValue(99L);
        } else {
            recommendUserVo.setFateValue(recommendUser.getScore().longValue());
        }

        return recommendUserVo;
    }


    //查询陌生人问题(聊一下)
    public String findStrangerQuestion(Long userId) {
        //1. 调用service查询陌生人问题
        Question question = questionService.findByUserId(userId);

        //2. 如果没有设置,给默认值
        if (question == null){
            return "这个小友很懒，什么都没有写呢~~~";
        }
        return question.getStrangerQuestion();
    }


    //谁看过我
    public List<VisitorVo> findVisitor() {
        //获取登录用户id
        Long userId = UserHolder.get().getId();

        //创建一个集合储存访客
        List<VisitorVo> visitorList = new ArrayList<>();

        //用户最后登录时间
        String lastAccessTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);

        if (lastAccessTime == null) {
            stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "");
            return visitorList;
        }

        //查询最近访客列表
        List<Visitor> visitorList1 = visitorService.findVisitorList(userId, lastAccessTime);

        // 重置redis中当前用户的上次访问时间=当前时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "");

        //组装
        if (CollectionUtil.isNotEmpty(visitorList1)) {
            for (Visitor visitor : visitorList1) {
                VisitorVo visitorVo = new VisitorVo();
                visitorVo.setUserInfo(userInfoService.findById(visitor.getVisitorUserId()));
                visitorVo.setFateValue(visitor.getScore().longValue());

                visitorList.add(visitorVo);
            }
        }

        return visitorList;

    }



    //上报用户地理位置
    public void saveUserLocation(Double longitude, Double latitude, String address) {

        Long userId = UserHolder.get().getId();

        userLocationService.save(userId, longitude, latitude, address);

    }


    //附近的人
    public List<NearUserVo> findNearUserList(String gender, Long distance) {

        Long userId = UserHolder.get().getId();

        //查询附近的用户id
        List<Long> nearUserList = userLocationService.findNearUserIdList(userId, distance);

        //创建集合储存nearUserVo
        List<NearUserVo> nearUserVoList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(nearUserList)) {
            for (Long aLong : nearUserList) {

                UserInfo userInfo = userInfoService.findById(aLong);

                //不是选中性别的不要
                if (!StrUtil.equals(userInfo.getGender(), gender)) {
                    continue;
                }

                //不要自己的id
                if (userId == aLong) {
                    continue;
                }
                NearUserVo nearUserVo = new NearUserVo();
                nearUserVo.setUserId(userInfo.getId());
                nearUserVo.setAvatar(userInfo.getAvatar());
                nearUserVo.setNickname(userInfo.getNickname());

                nearUserVoList.add(nearUserVo);
            }
        }

        return nearUserVoList;
    }


    //回复陌生人问题(给佳人打招呼)
    public void replyStrangerQuestion(String strangerId, String reply) {

        /*
            我的id
            我的昵称
            佳人的问题
            我的答案
        */

        //获取登录用户id
        Long userId = UserHolder.get().getId();

        //查询登录用户的信息
        UserInfo userInfo = userInfoService.findById(userId);

        //查询佳人的问题信息
        Question question = questionService.findByUserId(Long.parseLong(strangerId));

        String strangerQuestion = "这个小友很懒，什么都没有写哦~";

        //如果佳人问题为空，设置默认值
        if (question != null) {
            strangerQuestion = question.getStrangerQuestion();
        }

        //封装信息
        Map<String, String> map = new HashMap<>();
        map.put("userId", userId.toString());
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", strangerQuestion);
        map.put("reply", reply);

        String msg = JSONUtil.toJsonStr(map);

        huanXinTemplate.sendMsg(strangerId,msg);

    }


    //添加联系人
    public void saveContact(Long friendId) {

        //获取登录用户id
        Long userId = UserHolder.get().getId();

        //在mongo的friend表中储存好友关系
        friendService.save(userId, friendId);

        //在环信中保存两人好友关系
        huanXinTemplate.addContacts(userId,friendId);

    }



    //查询联系人
    public PageBeanVo findContact(Integer pageNum, Integer pageSize) {

        //查询登录用户id
        Long userId = UserHolder.get().getId();

        //在mongo中查找用户的好友集合
        PageBeanVo pageBeanVo = friendService.findContact(userId, pageNum, pageSize);

        //从集合中取出items
        List<Friend> friendList = (List<Friend>) pageBeanVo.getItems();

        //定义一个集合储存集合
        List<ContactVo> contactVoList = new ArrayList<>();

        //获取每个好友的信息
        if (CollectionUtil.isNotEmpty(friendList)) {
            for (Friend friend : friendList) {
                UserInfo userInfo = userInfoService.findById(friend.getFriendId());

                ContactVo contactVo = new ContactVo();
                contactVo.setUserInfo(userInfo);

                contactVoList.add(contactVo);
            }
        }

        //封装
        pageBeanVo.setItems(contactVoList);

        return pageBeanVo;
    }
}